package com.chenhy.springbootvuesmbms.service;

import com.chenhy.springbootvuesmbms.mapper.UserMapper;
import com.chenhy.springbootvuesmbms.pojo.Role;
import com.chenhy.springbootvuesmbms.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private RoleService roleService;

//    @Autowired
//    private PasswordEncoder passwordEncoder;

    @Transactional
    @Override
    public List<User> queryAllUser() {
        List<User> users = userMapper.queryAllUser();
        for (User user : users) {
            Role role = roleService.queryRoleById(user.getUserRole());
            user.setUserRoleName(role.getRoleName());
        }
        return users;
    }

    @Override
    public List<User> userFuzzyQuery(String condition) {
        List<User> users = userMapper.userFuzzyQuery(condition);
        for (User user : users) {
            Role role = roleService.queryRoleById(user.getUserRole());
            user.setUserRoleName(role.getRoleName());
        }
        return users;
    }

    @Override
    public int addUser(User user) {
//        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        user.setCreatedBy(loginUser.getId());
//        user.setModifyBy(loginUser.getId());
//        return userMapper.addUser(user);
        return 0;
    }

    @Override
    public int deleteUser(int id) {
        return userMapper.deleteUser(id);
    }

    @Transactional
    @Override
    public User queryUserById(int id) {
        User user = userMapper.queryUserById(id);
        Role role = roleService.queryRoleById(user.getUserRole());
        user.setUserRoleName(role.getRoleName());
        return user;
    }

    @Override
    public int updateUser(User user) {
//        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        user.setModifyBy(loginUser.getId());
//        return userMapper.updateUser(user);
        return 0;
    }

    @Override
    public int resetPasswordById(int id) {
        return userMapper.resetPasswordById(id);
    }

//    @Override
//    public Boolean revisePassword(LoginUser loginUser, String oldPassword, String newPassword) {
//        if (passwordEncoder.matches(oldPassword, userMapper.queryUserById(loginUser.getId()).getUserPassword())){
//            userMapper.revisePassword(loginUser.getId(), passwordEncoder.encode(newPassword));
//            return true;
//        } else {
//            return false;
//        }
//
//    }

    @Override
    public void flushCache(){

    }


}
